#!/bin/bash
source /etc/profile
#SHELL=/bin/bash
#PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# 其他备份服务器ip及其地址
REMOTE_SERVER="172.16.0.6"
REMOTE_USER="root"


# MySQL数据库信息
DB_HOST="172.16.0.16"
DB_PORT="13306"
DB_USER="root"
DB_PASSWORD="X*******"

# 备份文件的保存路径
BACKUP_DIR="/data/backup/sql/$(date +%Y%m%d)"
# 创建备份文件保存目录
mkdir -p "${BACKUP_DIR}/"
#数组
dbNames=("nacos" "bpm_server")
LOG_FILE=${BACKUP_DIR}/info.log


#记录信息
echo "当前路径：$PATH,当前执行者：$USER" >>  ${LOG_FILE}

start_time=$(date +"%Y-%m-%d %H:%M:%S.%3N")
start_seconds=$(date -d "$start_time" +%s%3N)
#echo "$start_time 全量数据库备份开始" >> ${LOG_FILE}

BACKUP_FILE="${BACKUP_DIR}/backup_all_$(date +%Y%m%d%H%M%S).sql.gz"
ssh ${REMOTE_USER}@${REMOTE_SERVER} "mkdir -p ${BACKUP_DIR}"




# 使用for循环遍历数组
for dbName in "${dbNames[@]}"
do
  
  BACKUP_FILE="${BACKUP_DIR}/${dbName}_$(date +%Y%m%d%H%M%S).sql.gz"
  # 使用mysqldump命令备份数据库
  
  sudo docker exec mysql8 sh -c "mysqldump -u${DB_USER} -h${DB_HOST} --port=${DB_PORT} -p${DB_PASSWORD} ${dbName}" | gzip > ${BACKUP_FILE}

  # 检查备份是否成功
  if [ $? -eq 0 ]; then

          echo "$(date +"%Y-%m-%d %H:%M:%S.%3N") 数据库备份成功：${BACKUP_FILE}" >> ${LOG_FILE}

          scp ${BACKUP_FILE} ${BACKUP_USER}@${REMOTE_SERVER}:${BACKUP_DIR}
          echo "$(date +"%Y-%m-%d %H:%M:%S.%3N") 发送文件[${BACKUP_FILE}]到远程[${REMOTE_SERVER}]服务器" >>  ${LOG_FILE}

  else
          echo "$(date +"%Y-%m-%d %H:%M:%S.%3N") 数据库备份失败：${BACKUP_FILE}" >> ${LOG_FILE}
  fi
  
  #zip ${dbName}.zip ${dbName}.sql
  #rm -rf ${dbName}.sql
 
done



